//引入封装好的接口
import { getUserlist, getUsercount } from '@/request/api'
//封装一个state接口
interface userSate {
    userlist: Array<object>
    total: Array<object>
    size: Array<object>
    page: Array<object>
}

//封装state
const state = {
    userlist: [],
    total: 0,//总条数
    size: 2,//页面显示的条数
    page: 1,//具体传输那个页面
}
//getters
const getters = {
    getUserList(state: userSate) {
        return state.userlist
    },
    getCount(state: userSate) {
        return state.total
    },
    // 把size传输到组件
    getSize(state: userSate) {
        return state.size
    }
}
//mutations
const mutations = {
    REQ_ROLELIST(state: userSate, payload: any) {
        state.userlist = payload
    },
    REQ_COUNT(state: userSate, payload: any) {
        state.total = payload
    },
    REQ_PAGE(state: userSate, payload: any) {
        state.page = payload
    }
}

//行动
const actions = {
    //封装一个行动
    changeUserAction(context: any) {
        getUserlist({
            size: context.state.size,
            page: context.state.page
        })
            .then((res: any) => {
                console.log(res, '列表');
                if (res.code == 200) {
                    let list = res.list ? res.list :[]
                      // 由于删除非第一页，只有最后一天数据的时候出现了bug所以我们要用条件判断去控制
                // 给page-1
                if(context.state.page!=1&&list.length==0){
                    // 从新去修改页码
                    context.dispatch('getUserPageAction',context.state.page-1)
                }
                // 提交一个mutation
                    context.commit('REQ_ROLELIST', list)
                }
            })
    },
    // 封装一个获取总数的行动
    getCountAction({ commit }:any) {
        getUsercount()
            .then((res:any) => {
                console.log(res, '总条数');
                if (res.code == 200) {
                    commit('REQ_COUNT',res.list[0].total)
                }

            })
    },
    // 封装一个切换页码的行动
    getUserPageAction(context:any,payload:any){
        console.log(context,'context');
        // 修改page，并且从新调用列表行动
        context.commit('REQ_PAGE',payload)
        context.dispatch('changeUserAction')
    }
}


//导出封装好的属性
export default {
    state,
    getters,
    mutations,
    actions,
    //开一个命名空间
    namespaced: true
}